/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Weibull.java
 *
 * Created on 18/05/2010, 17:40:43
 */

package br.leiam.eolica.graficos;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import sun.misc.BASE64Encoder;
import br.leiam.eolica.BD.Consulta;
import br.leiam.eolica.BD.ConsultaJfreeReady;
import br.leiam.eolica.excecoes.EolicaException;
import br.leiam.eolica.funcoes.MinimosQuadrados;

/**
 * 
 * @author Denis
 */
public class Weibull extends javax.swing.JPanel {
	private org.jfree.data.jdbc.JDBCXYDataset chartDataset;
	private XYDataset chartDataset2;
	private JFreeChart chart;
	private Consulta tableModel, consulta;
	private ConsultaJfreeReady tableModel2;
	private String QUERY = "";
	private String QUERY1 = "";
	private MinimosQuadrados minQuadrados = new MinimosQuadrados();
	private double[] frequenciaRelativa;
	private double[] velocidadeVentoMedio;
	private String QueryConsulta;

	public Weibull(String TABLE_NAME,  String DataInicio,
			String DataFim, int altura, int tamx, int tamy)
			throws EolicaException {
		initComponents();
		this.setSize(tamx, tamy);

		String coluna1 = RosaDosVentosVelocidades.getColunaVelocidade(altura);
		String sAltura = coluna1;

		String ajuste = "/10";
		if (coluna1.equals("p1a"))
			ajuste = "*0.0008+0.22";
		double x, xx = .2;
		double passo = xx;
		double fim = 20;
		for (x = 0; x < fim; x = x + xx) {
			String um = String.valueOf(x);
			String dois = String.valueOf(x + xx);

			QUERY = QUERY + "select '" + String.valueOf(x + xx)
					+ "' as velocidade, ((select count(*) from " + TABLE_NAME
					+ " where " + coluna1 + ajuste + " >= " + um + " and "
					+ coluna1 + ajuste + " < " + dois
					+ " and datahora between timestamp('" + DataInicio
					+ "') and timestamp('" + DataFim
					+ "')) / (select count(*) from " + TABLE_NAME
					+ " where datahora between timestamp('" + DataInicio
					+ "') and timestamp('" + DataFim
					+ "'))) as frequencia union \n";

		}
		QUERY = QUERY + "select '" + String.valueOf(x + xx)
				+ "' as velocidade,  ((select count(*) from " + TABLE_NAME
				+ " where " + coluna1 + ajuste + " >" + String.valueOf(x + xx)
				+ " and datahora between timestamp('" + DataInicio
				+ "') and timestamp('" + DataFim
				+ "')) / (select count(*) from " + TABLE_NAME
				+ " where datahora between timestamp('" + DataInicio
				+ "') and timestamp('" + DataFim + "'))) as frequencia";

		for (x = 0; x < fim; x = x + 1) {
			String um = String.valueOf(x);
			String dois = String.valueOf(x + 1);

			QUERY1 = QUERY1 + "select " + String.valueOf((int) x + .5)
					+ " as velocidade, ((select count(*) from " + TABLE_NAME
					+ " where " + coluna1 + ajuste + " >= " + um + " and "
					+ coluna1 + ajuste + " < " + dois
					+ " and datahora between timestamp('" + DataInicio
					+ "') and timestamp('" + DataFim
					+ "')) / (select count(*) from " + TABLE_NAME
					+ " where datahora between timestamp('" + DataInicio
					+ "') and timestamp('" + DataFim
					+ "')))*100 as frequencia union \n";
		}
		QUERY1 = QUERY1 + "select 20 as velocidade,  ((select count(*) from "
				+ TABLE_NAME + " where " + coluna1 + ajuste
				+ " >20 and datahora between timestamp('" + DataInicio
				+ "') and timestamp('" + DataFim
				+ "')) / (select count(*) from " + TABLE_NAME
				+ " where datahora between timestamp('" + DataInicio
				+ "') and timestamp('" + DataFim + "')))*100 as frequencia";

		try {

			tableModel = new Consulta(QUERY);

		} catch (Exception ex) {
			br.leiam.eolica.util.Logger.getInstance().log("Erro disparado: " + ex.toString());
			System.out.println(ex.toString());
		}
		int numeroDeLinhas = 0;
		try {
			numeroDeLinhas = tableModel.getNumeroDeLinhas();
		} catch (NullPointerException e) {
			
		}
		
		
		frequenciaRelativa = new double[numeroDeLinhas];
		velocidadeVentoMedio = new double[numeroDeLinhas];

		for (int i = 0; i < numeroDeLinhas; i++) {
			try {
				velocidadeVentoMedio[i] = Double.parseDouble(tableModel.getValorEm(	i, 0).toString());
			} catch (NullPointerException e) {
				velocidadeVentoMedio[i] = 0;
			}
			
			try {
				frequenciaRelativa[i] = Double.parseDouble(tableModel.getValorEm(i,1).toString());
			} catch (NullPointerException e) {
				frequenciaRelativa[i] = 0;
			}			
		}

		minQuadrados.calculaConstantes(frequenciaRelativa,
				velocidadeVentoMedio, passo);

		double k = minQuadrados.k, c = minQuadrados.c;
		int n = velocidadeVentoMedio.length;
		double[] Fv = new double[n];
		for (int i = 0; i < n; i++) {
			Fv[i] = 0;
			Fv[i] = (k / c) * Math.pow((velocidadeVentoMedio[i] / c), k - 1)
					* Math.exp(-Math.pow((velocidadeVentoMedio[i] / c), k));
			// System.out.printf("\n %.3f;     %.3f;",
			// velocidadeVentoMedio[i],Fv[i]);

		}
		try {
			tableModel2 = new ConsultaJfreeReady(QUERY1);
			chartDataset = tableModel2.getChartDataset();

		} catch (Exception ex) {
			Logger.getLogger(Weibull.class.getName()).log(Level.SEVERE, null,
					ex);
		}

		XYSeries series = new XYSeries("Frequencia");

		for (int h = 0; h < chartDataset.getItemCount(0); h++) {
			series.add(chartDataset.getX(0, h), chartDataset.getY(0, h));

		}

		XYSeriesCollection datasetChart = new XYSeriesCollection(series);

		chartDataset2 = createDataSet2(velocidadeVentoMedio, Fv);
		chart = org.jfree.chart.ChartFactory.createXYLineChart(
				"DISTRIBUICAO DE WEIBULL", "Velocidade do Vento (m/s)",
				"Frequencia (%)", chartDataset2,
				org.jfree.chart.plot.PlotOrientation.VERTICAL, false, true,
				true);
		chart.getTitle().setFont(
				chart.getTitle().getFont().decode("Arial-BOLD"));
		chart.getTitle().setFont(
				chart.getTitle().getFont()
						.deriveFont((float) (this.getWidth()) * 11f / 350f));

		ChartPanel chartPanel = new ChartPanel(chart);
		jPanel4.add(chartPanel);
		XYPlot plot = chart.getXYPlot();
		plot.setBackgroundPaint(Color.white);
		plot.setDomainGridlinePaint(Color.gray);
		plot.setRangeGridlinePaint(Color.gray);
		plot.getRenderer(0).setSeriesStroke(0, new BasicStroke(2f));
		// plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
		// plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

		org.jfree.chart.renderer.xy.XYItemRenderer renderer2 = new org.jfree.chart.renderer.xy.XYBarRenderer(
				.2);

		plot.getRenderer(0).setSeriesPaint(0, Color.blue);
		// renderer2.setSeriesShape(0, null);
		// renderer2.setSeriesStroke(0, null);

		renderer2.setSeriesPaint(0, Color.red);
		plot.setRenderer(1, renderer2);

		plot.setDataset(1, datasetChart);

		// plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

		NumberFormat formatador = NumberFormat.getInstance();
		formatador.setMaximumFractionDigits(2);
		String temp;
		double media = 0;
		QueryConsulta = "select 0,0 union select 0,avg(`r`.`" + coluna1 + "`)"
				+ ajuste + " as media from " + TABLE_NAME
				+ " r where datahora between timestamp('" + DataInicio
				+ "') and timestamp('" + DataFim + "')";
		// QueryConsulta =
		// "select 0,0 union select 0,avg("+coluna1+"`)/10 as media from "+TABLE_NAME+" r where datahora between timestamp('"+DataInicio+"') and timestamp('"+DataFim+"')";
		consulta = new Consulta(QueryConsulta);
		try {
			temp = consulta.getValorEm(1, 1).toString();
			media = Double.valueOf(temp);
		} catch (Exception e) {
		}

		/*
		 * consulta = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
		 * USERNAME, PASSWORD, QueryConsulta); temp = consulta.getValueAt(1,
		 * 1).toString(); media = Double.valueOf(temp);
		 */
		
				
		Font fonte = lblResume.getFont();
		float tamanhoFonte = this.getWidth() * 8 / 300;
		lblResume.setFont(fonte.deriveFont(tamanhoFonte));
		lblResume.setText("Altura = " + altura + "m    Vmedia = "
				+ formatador.format(media) + "m/s  Vweibull k = "
				+ (new Double(k).isNaN()? "0":formatador.format(k))+ "   Weibull C = "
				+ (new Double(c).isNaN()? "0":formatador.format(c))+ " m/s");

		jPanel3.setBounds(0, this.getHeight() - 36, this.getWidth(), 36);
		lblResume.setBounds(0, 0, jPanel3.getWidth(), jPanel3.getHeight());
		jPanel4.setBounds(0, 0, this.getWidth(),
				this.getHeight() - jPanel3.getHeight());
		chartPanel.setBounds(jPanel4.getBounds());
	}


	private XYDataset createDataSet2(double[] velVento, double[] Fv) {
		XYSeries serie1 = new XYSeries("Weibull");

		for (int i = 0; i < velVento.length; i++) {
			serie1.add(velVento[i], Fv[i] * 100);

		}
		XYDataset xyDataset = new XYSeriesCollection(serie1);
		return xyDataset;
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jPanel4 = new javax.swing.JPanel();
		jPanel3 = new javax.swing.JPanel();
		lblResume = new javax.swing.JLabel();

		setBackground(new java.awt.Color(255, 255, 255));

		jPanel4.setBackground(new java.awt.Color(255, 255, 255));
		jPanel4.setLayout(new java.awt.BorderLayout());

		jPanel3.setBackground(new java.awt.Color(255, 255, 255));

		lblResume.setFont(new java.awt.Font("Arial", 0, 8)); // NOI18N
		lblResume.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
		lblResume.setText("Altura = xm");
		lblResume.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				lblResumeMouseClicked(evt);
			}
		});

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(
				jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel3Layout
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(lblResume,
								javax.swing.GroupLayout.DEFAULT_SIZE, 397,
								Short.MAX_VALUE).addContainerGap()));
		jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel3Layout
						.createSequentialGroup()
						.addContainerGap()
						.addComponent(lblResume)
						.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE,
						417, Short.MAX_VALUE)
				.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addComponent(jPanel4,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										266, Short.MAX_VALUE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jPanel3,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)));
	}// </editor-fold>//GEN-END:initComponents

	private void lblResumeMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_lblResumeMouseClicked

	}// GEN-LAST:event_lblResumeMouseClicked

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JPanel jPanel3;
	private javax.swing.JPanel jPanel4;
	private javax.swing.JLabel lblResume;
	// End of variables declaration//GEN-END:variables

	public String getBase64String(){


	    String figura="";

	    try {
	        double escalaX=1,escalaY=1;
	        Component co = this;
	        BufferedImage bi = new BufferedImage((int) (co.getSize().getWidth()*escalaX),
	        (int) (co.getSize().getHeight()*escalaY), BufferedImage.TYPE_INT_RGB);
	        Graphics2D g2d = bi.createGraphics();
	        g2d.scale(escalaX, escalaY);
	        co.paint(g2d);

	        byte[] figBytes;

	            figBytes = ChartUtilities.encodeAsPNG(bi);

	        BASE64Encoder encoder = new BASE64Encoder();
	        figura = encoder.encode(figBytes);
	   } catch (Exception ex) {
	            Logger.getLogger(Weibull.class.getName()).log(Level.SEVERE, null, ex);
	        }
	           return figura;
	}
	
}
